package servlet;

import impl.BooksImpl;
import impl.CommentImpl;
import impl.FeedbackDaoImpl;
import impl.UsersDaoImpl;
import impl.VisitDaoImpl;

import java.awt.print.Book;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.BooksDao;
import dao.CommentDao;
import dao.FeedbackDao;
import dao.UsersDao;
import dao.VisitDao;
import entity.Books;
import entity.Comment;
import entity.Feedback;
import entity.Users;
import entity.Visit;

public class UserInfoServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

		/****** 初始化部分 ******/
		//设置编码格式，前端后台统一是utf-8 
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		HttpSession httpSession = request.getSession();
		String opr = request.getParameter("opr");
		PrintWriter out = response.getWriter();

		UsersDao userDao=new UsersDaoImpl(); 
		BooksDao bookDao=new BooksImpl();
		CommentDao commentDao=new CommentImpl(); 
		String remoteIp=request.getRemoteAddr();//获取客户端的ip    
		VisitDao visitDao=new VisitDaoImpl();
		FeedbackDao feedbackDao=new FeedbackDaoImpl();
		
		out.print("<script type='text/javascript'>"); 
		if("youke".equals(opr)){ 
			List<Books> books=bookDao.allBooks();
			httpSession.setAttribute("books",books);
			out.print("location.href='index.jsp';");

			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			Visit visit=new Visit();
			visit.setId(uuid);
			visit.setVisit_date(geDate());
			visit.setVisit_type(remoteIp);
			visitDao.addVisit(visit);
			int count=visitDao.allVisit().size();
			httpSession.setAttribute("visits",count);
		}
		else if("login".equals(opr)){
			String userInfoId = request.getParameter("loginName");
			String UserInfoPwd = request.getParameter("loginPwd");
			Users userinfo=new Users();
			userinfo.setUser_name(userInfoId);
			userinfo.setUser_pwd(UserInfoPwd);
			Users user =userDao.LoginUser(userinfo);
			if(user!=null){
				out.print("alert('登录成功！');");	
				List<Books> books=bookDao.allBooks();
				httpSession.setAttribute("books",books);
				httpSession.setAttribute("user",user);
				//判断身份进入不同页面 0管理员 管理文章 评论 1用户 可以进行评论
				if(user.getUser_role().equals("0")){ 
					out.print("location.href='manager.jsp';");
					List<Comment> comments=commentDao.commentAll();
					httpSession.setAttribute("comments",comments);
					httpSession.setAttribute("allfeedback",feedbackDao.allFeedback());
				}else{
					out.print("location.href='index.jsp';"); 
				} 
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				Visit visit=new Visit();
				visit.setId(uuid);
				visit.setVisit_date(geDate());
				visit.setVisit_type(remoteIp);
				visitDao.addVisit(visit); 
				int count=visitDao.allVisit().size();
				httpSession.setAttribute("visits",count);
			}else{
				out.print("alert('用户名或密码错误！');");
				out.print("location.href='login.jsp';");
			} 
		}else if("detailsbooks".equals(opr)){ 
			String book_details = request.getParameter("detailsbooksbookid");

			List<Books> books=bookDao.allBooks();
			httpSession.setAttribute("books",books);
			Books book=new Books();
			for (Books b : books) {
				if(b.getId().equals(book_details)){
					book=b;
					break;
				}
			} 
			httpSession.setAttribute("books",books);
			httpSession.setAttribute("bookdetails",book);
			List<Comment> comments=commentDao.commentByBook_id(request.getParameter("detailsbooksbookid"));
			httpSession.setAttribute("comments",comments);  
			out.print("location.href='subpage.jsp';");
		}else if("register".equals(opr)){
			String name = request.getParameter("user_name");
			String pwd = request.getParameter("user_password");
			Users user=new Users();
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			user.setId(uuid);
			user.setUser_name(name);
			user.setUser_pwd(pwd);
			user.setUser_role("1"); 
			int addflog=userDao.addUser(user); 
			httpSession.setAttribute("user",user);
			if(addflog>0){ 
				List<Books> books=bookDao.allBooks();
				httpSession.setAttribute("books",books);
				out.print("alert('账号注册成功！');");
				out.print("location.href='index.jsp';");
			}else{ 
				out.print("alert('账号注册失败！');");
				out.print("location.href='register.jsp';");
			}
		}else if("addbook".equals(opr)){

			String uuid = UUID.randomUUID().toString().replaceAll("-", ""); 
			Books book=new Books(); 
			String imgurl="";
			// step1,创建一个DiskFileItemFactory对象
			// 为解析器提供解析时的缺省的配置。
			DiskFileItemFactory dfif = new DiskFileItemFactory(); 
			// step2,创建一个解析器
			ServletFileUpload sfu = new ServletFileUpload(dfif);
			sfu.setHeaderEncoding("ISO8859_1");
			// step3,使用解析器解析
			try {
				// FileItem对象封装了一个表单域当中的所有的
				// 数据。

				List<FileItem> items = sfu.parseRequest(request);
				for (int i = 0; i < items.size(); i++) {
					FileItem item = items.get(i); 
					// 要判断是一个普通的表单域还是
					// 上传文件域
					if (item.isFormField()) {

						// 是一个普通的表单域
						String name = new String(item.getFieldName().getBytes("ISO8859_1"),"utf-8");
						String value = new String(item.getString().getBytes("ISO8859_1"),"utf-8");
						System.out.println(name + ":" + value);
						if(name.equals("book_date")){
							book.setBook_date(name); 
						}
						if(name.equals("book_dateails")){ 
							book.setBook_dateails(value);
						}
						if(name.equals("book_number")){ 
							book.setBook_number(value); 
						}
						if(name.equals("book_user_name")){ 
							book.setBook_user_name(value); 
						}
						if(name.equals("book_phone")){ 
							book.setBook_phone(value); 
						}
					} else {
						// 上传文件域,要将文件保存在服务器端
						ServletContext sc = this.getServletContext();

						// 获得实际部署时物理路径
						String path = sc.getRealPath("file");
						System.out.println(path);
						// 获得上传文件的名称
						String fileName = item.getName(); 
						String geshi=fileName.substring(fileName.lastIndexOf(".")); 
						fileName=uuid+geshi;
						File file = new File(path + "//" + fileName); 
						item.write(file);

						imgurl="file//"+fileName;
					}
				}

				//图片保存地址加名字
				book.setId(uuid); 
				book.setBook_imgurl(imgurl);
				int floag=bookDao.addBooks(book);
				if(floag>0){ 
					out.print("alert('书籍添加成功！');");
				}else{ 
					out.print("alert('书籍添加失败！');");
				}
				List<Books> books=bookDao.allBooks();
				httpSession.setAttribute("books",books);
				out.print("location.href='notices.jsp';");
			} catch (Exception e) {
				e.printStackTrace();

			}
		}else if("delBook".equals(opr)){
			Books book=new Books();
			book.setId(request.getParameter("book_id"));
			int flog=bookDao.delBooks(book); 
			if(flog>0){ 
				out.print("alert('书籍删除成功！');");
			}else{ 
				out.print("alert('书籍删除失败！');");
			}
			List<Books> books=bookDao.allBooks();
			httpSession.setAttribute("books",books);
			out.print("location.href='notices.jsp';");
		}else if("delComment".equals(opr)){ 
			int flog=commentDao.delComment(request.getParameter("comment_id"));
			if(flog>0){ 
				out.print("alert('评论删除成功！');");
			}else{ 
				out.print("alert('评论删除失败！');");
			}
			List<Comment> comments=commentDao.commentAll();
			httpSession.setAttribute("comments",comments);
			out.print("location.href='comments.jsp';");
		}else if("addcomment".equals(opr)){
			Comment comment=new Comment(); 
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			comment.setId(uuid);
			comment.setBook_key(request.getParameter("book_key")); 
			comment.setCommentdate(geDate());
			comment.setMsg(request.getParameter("msg"));
			comment.setName(request.getParameter("name"));
			int flog=commentDao.addComment(comment);
			if(flog>0){ 
				out.print("alert('评论成功！');");
			}else{ 
				out.print("alert('评论失败！');");
			}
			List<Comment> comments=commentDao.commentByBook_id(request.getParameter("book_key"));
			httpSession.setAttribute("comments",comments);  
			String book_details = request.getParameter("book_key"); 
			List<Books> books=bookDao.allBooks();
			httpSession.setAttribute("books",books);
			Books book=new Books();
			for (Books b : books) {
				if(b.getId().equals(book_details)){
					book=b;
					break;
				}
			}  
			httpSession.setAttribute("bookdetails",book);
			out.print("location.href='subpage.jsp';");
		}else if("outlog".equals(opr)){
			httpSession.removeAttribute("user");
			out.print("alert('成功注销登录!');");
			out.print("location.href='login.jsp';");
		}else if("addfeedback".equals(opr)){ 
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String msg=request.getParameter("msg");
			String date=geDate();
			Feedback feedback=new Feedback();
			feedback.setId(uuid);
			feedback.setDate(date);
			feedback.setMsg(msg);
			int flag=feedbackDao.addFeedback(feedback);
			if(flag>0){ 
				out.print("alert('反馈成功,感谢您的宝贵意见！');");
			}else{
				out.print("alert('反馈失败！');");
			} 
				out.print("location.href='index.jsp';");  
				List<Books> books=bookDao.allBooks();
				httpSession.setAttribute("books",books);
		}
		out.print("</script>");
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}


	public String geDate() {  
		Date ss = new Date();     
		SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
		return format0.format(ss.getTime());
	}  
}
